package com.neo.service;


import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.neo.entity.errorMessage.RespErrorCode;
import com.neo.util.ErrorFileUtil;
import com.neo.util.ReadFromFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.neo.util.DjsStringUtil;

@Service
public class DjsRecordFileService {

    protected static Logger logger= LoggerFactory.getLogger(DjsRecordFileService.class); 
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //String batch = "000001";

    public String generalFile(String batch, String userAccountId) throws Exception {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT " +
                "a.PROJECT_NO AS PRODUCT_ID," +
                "a.PAY_NO AS ORDER_ID, " +
                "a.ENABLE_AMT as ENABLE_AMT, " +
                "a.MAKE_LOAN_TIME as MAKE_LOAN_TIME, " +
                //"b.INTEREST_PAY_TYPE as INTEREST_PAY_TYPE, " +
                "a.INVEST_RATE as INVEST_RATE, " +
                "a.LOAN_MENT as LOAN_MENT " +
                //"b.INTEREST_PAY_DAY as INTEREST_PAY_DAY " +
                "from jx_invest_project a " +
                //"INNER JOIN jx_invest_project b ON a.PRODUCT_ID = b.PROJECT_NO " +
                "where a.MAKE_LOAN_TIME IS NOT NULL and id>=371 ", new Object[]{});

        List<String> resList = new ArrayList<>();
        for (Map map : list) {
            String inv_account_id = userAccountId;
            String product_id = (String) map.get("PRODUCT_ID");
            String order_id = (String) map.get("ORDER_ID");//借款流水号，标的迁移使用的orderId存PAY_NO
            BigDecimal inv_amount = (BigDecimal) map.get("ENABLE_AMT");
            Date inv_date = (Date) map.get("MAKE_LOAN_TIME");
            Date interest_start_date = (Date) map.get("MAKE_LOAN_TIME");
            String interest_pay_type = (String) map.get("INTEREST_PAY_TYPE");
            BigDecimal year_rate = (BigDecimal) map.get("INVEST_RATE");
            Integer loanMent = (Integer) map.get("LOAN_MENT");
            Calendar date = Calendar.getInstance();
            date.setTime(inv_date);
            date.set(Calendar.DATE, date.get(Calendar.DATE) + loanMent);
            Date interest_end_date = date.getTime();
            String interest_pay_day = (String) map.get("INTEREST_PAY_DAY");

            order_id = DjsStringUtil.COINSTCODE + "0000" + order_id;
            if (inv_amount == null) {
                continue;
            }

            inv_amount = inv_amount.setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_DOWN);//去2位小数再变整数
            year_rate = year_rate.setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100000")).setScale(0, BigDecimal.ROUND_DOWN);//去2位小数再变整数
            String res = DjsStringUtil.BANKID    //银行代号
                    + batch //批次号
                    + DjsStringUtil.fillBlank(inv_account_id, 19) //债权持有人电子账号
                    + DjsStringUtil.fillBlank(DjsStringUtil.FUISSUER, 4)    //产品发行方
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 6) //标的号-不用
                    + DjsStringUtil.fillBlank(order_id, 40) //申请流水号
                    + DjsStringUtil.fillLeftZero(inv_amount.toString(), 13) //当前持有债权金额
                    + DjsStringUtil.fillBlank(DjsStringUtil.dateHandle(inv_date), 8)    //债权获取日期
                    + DjsStringUtil.fillBlank(DjsStringUtil.dateHandle(interest_start_date), 8)    //起息日
                    + DjsStringUtil.fillDefault("2", "0")//付息方式
                    + DjsStringUtil.fillBlank("", 2)        //利息每月支付日
                    + DjsStringUtil.fillBlank(getEndTime(product_id), 8)        //产品到期日
                    + DjsStringUtil.fillLeftZero(year_rate.toString(), 8)    //预期年化收益率
                    + "156"        //币种
                    + DjsStringUtil.fillBlank(product_id, 40) //标的号
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 60)//保留域
                    ;
            System.out.println(res);

            byte[] bs = res.getBytes("GBK");
            if (bs.length != 230) {
                System.out.println("长度错误");
            }
            resList.add(res);
        }

        System.out.println("生成文件行数" + resList.size());

        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String strDate = dateFormater.format(date);
        String fileName = DjsStringUtil.FILE_PATH + DjsStringUtil.BANKID + "-BID-" + batch + "-" + strDate;
        DjsStringUtil.writeStringToFile(resList, batch, fileName);
        System.out.println("生成文件:" + fileName);

        return fileName;
    }

    public Map<String, String> readResFile(List<String> list) throws Exception {
        int res_f = 0;
        int res_s = 0;
        Map<String, String> result = new HashMap<>();
        List<String> errData = new ArrayList<>();
        for (String str : list) {
            String rspCode = DjsStringUtil.cutByGBK(str, 160, 2);
            if (rspCode.equals("00")) {
                insertRecord(str);
                res_s++;
            } else {
                String errName = "";
                switch (rspCode) {
                    case "14":
                        errName = "无效账号";
                        break;
                    case "93":
                        errName = "姓名校验错误";
                        break;
                    case "99":
                        errName = "其他错误原因";
                        break;
                    default:
                        break;
                }
                res_f++;
                errData.add(new StringBuffer("失败原因：").append(errName).append("，原数据为=========>").append(str).toString());
            }
            logger.info("{}/{}",res_s,res_f);
            System.out.println("=="+res_s+"/"+res_f);
        }
        if (errData.size() > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            result = ErrorFileUtil.handle(errData, "BIDRESPErrorDataFile" + simpleDateFormat.format(new Date()) + "00" + res_f + res_s);
        }
        System.out.println("失败F条数" + res_f + "");
        System.out.println("成功S条数" + res_s + "");
        System.out.println("处理总数" + list.size() + "");
        result.put("失败F条数", res_f + "");
        result.put("成功S条数", res_s + "");
        result.put("处理总数", list.size() + "");
        return result;
    }

    private String getEndTime(String payNo) {
        List listCsv = ReadFromFile.readFileByLinesGbk("D:/点金石/新债权信息/还款日.csv");//地址变更
        List<Map<String, String>> args = new ArrayList<>();
        Map<String, String> da = new HashMap<>();
        for (int i = 1; i < listCsv.size(); i++) {
            String[] s = (String[]) listCsv.get(i);
            String pay_no = s[0];
            String endDate = s[1];
            String currnTurn = s[2];
            if (pay_no.equals(payNo)) {
                Map<String, String> data = new HashMap<>();
                data.put(currnTurn, endDate);
                args.add(data);
            }
        }
        int i = 0;
        for (Map<String, String> map : args) {
            Set<String> keys = map.keySet();
            for (String key : keys) {
                if (Integer.parseInt(key) > i) {
                    da.put("data", map.get(key));
                }
            }
        }
        if (da.size() > 0 && da.containsKey("data")) {
            return da.get("data").replaceAll("-", "");
        } else {
            return "";
        }
    }


    //	public static String formatString(String in,int len) {
//		return String.format("%1$-"+len+"s", in);
//	}


    public void insertRecord(String data) throws UnsupportedEncodingException {
        String sql = "INSERT INTO jx_inv_record " +
                "(USERNAME, INV_ACCOUNT_ID, BOR_ACCOUNT_ID, PRODUCT_ID, "
                + "ORDER_ID, AUTH_CODE, YEAR_RATE, INV_AMOUNT, "
                + "INV_DAY, INV_DATE, INV_STATUS)" +
                "VALUES  (?, ?, ?, ?,   ?, ?, ?, ?,   ?, ?, ?)";
        String productId = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 182, 40), false);
        String orderId = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 39, 40), false);
        String authCode = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 162, 20), false);
        String invAmount = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 79, 13), true);
        String invDate = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 152, 8), false);
        String inv_account_id = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 10, 19), false);
        String sqlForProject = "SELECT * FROM jx_invest_project WHERE PROJECT_NO = ?";
        List<Map<String, Object>> projects = jdbcTemplate.queryForList(sqlForProject, productId);
        String borrower_account_id;
        String year_rate;
        String loan_ment;
        if (projects != null && projects.size() > 0) {
            Map<String, Object> project = projects.get(0);
            year_rate = project.get("INVEST_RATE") + "";
            borrower_account_id = project.get("BORROWER_ACCOUNT_ID") + "";
            loan_ment = project.get("LOAN_MENT") + "";
        } else return;
        String sqlForUser = "SELECT * FROM jx_account_info WHERE ACCOUNT_ID = ?";
        List<Map<String, Object>> invUsers = jdbcTemplate.queryForList(sqlForUser, inv_account_id);
        String userName;
        if (invUsers != null && invUsers.size() > 0) {
            Map<String, Object> invUser = invUsers.get(0);
            userName = invUser.get("USERNAME") + "";
        } else return;
        jdbcTemplate.update(sql, userName,  inv_account_id, borrower_account_id, productId, orderId, authCode, year_rate, invAmount, loan_ment, invDate, "INVI");
    }

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        List<String> list = ReadFromFile.readFileGBK(new FileInputStream(new File("D:/点金石/3005-BIDRESP-000001-20171220")));
        for (String data : list) {
            String productId = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 182, 40), false);
            String orderId = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 39, 40), false);
            String authCode = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 162, 20), false);
            String invAmount = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 79, 13), true);
            String invDate = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 152, 8), false);
            String inv_account_id = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(data, 10, 19), false);
            System.out.println("");
        }
    }
}